package cn.rengy.tpa.wxmp.material;

import java.io.File;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;

/**
 * 临时素材管理 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727
 * 	1、临时素材media_id是可复用的。
	2、媒体文件在微信后台保存时间为3天，即3天后media_id失效。
	3、上传临时素材的格式、大小限制与公众平台官网一致。
	图片（image）: 2M，支持PNG\JPEG\JPG\GIF格式
	语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
	视频（video）：10MB，支持MP4格式
	缩略图（thumb）：64KB，支持JPG格式
 */
public class MediaFile {
	//新增临时素材
	private static final String UPLOAD = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=";
	//获取临时素材
	private static final String DOWNLOAD = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="; 
	private static final String PARAM_FILE = "media";
	private static final String PARAM_MEDIA_ID = "media_id";
	private static final String PARAM_TYPE = "type";
	private static final String PARAM_CREATE_TIME = "created_at";
	
	private MaterialType type;
	private File file;
	private String mediaId;  //3天失效
	private String createdTimestamp;//文件创建时间戳，上传之后返回
	
	
	/**
	 * 文件上传url
	 * @return
	 */
	private String uploadUrl(String token){
		String url = UPLOAD + token + "&" 
	              + PARAM_TYPE + "=" + this.type.name();
		return url;
	}
	
	/**
	 * 文件下载url
	 * @return
	 */
	private String downloadUrl(String token){
		String url = DOWNLOAD + token + "&" 
	         + PARAM_MEDIA_ID + "=" + this.mediaId;
		return url;
	}
	
	/**
	 * 文件上传
	 * success: {"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}
	 * error:   {"errcode":40004,"errmsg":"invalid media type"}
	 * @return  media_id  成功返回 media_id, 失败返回null
	 */
	public String upload(File file,MaterialType type,String token){
		this.file = file;
		this.type = type;
		String url = uploadUrl(token);
		String result = HttpUtils.postFile(url,PARAM_FILE, file);
		parseUploadResult(result);
		if(StringUtils.isNotBlank(this.mediaId))
			return this.mediaId;
		return null;
	}
	
	private void parseUploadResult(String result){
		JSONObject jsonObject = JSONObject.parseObject(result);
		if(jsonObject.containsKey(PARAM_MEDIA_ID)){
			this.mediaId = jsonObject.getString(PARAM_MEDIA_ID);
			this.createdTimestamp = jsonObject.getString(PARAM_CREATE_TIME);
		}
		else{
			this.mediaId = null;
			this.createdTimestamp = null;
		}
	}
	
	/**
	 * 文件下载
	 * @return  byte[]
	 */
	public byte[] download(String mediaId,String token){
		this.mediaId = mediaId;
		String url = downloadUrl(token);
		byte[] fb = HttpUtils.getFile(url);
		if(fb == null || fb.length == 0)
			return null;
		return fb;
	}

	public MaterialType getType() {
		return type;
	}

	public String getMediaId() {
		return mediaId;
	}

	public String getCreatedTimestamp() {
		return createdTimestamp;
	}
	
	
}
